/*************************************************
 *FileName:      friendpicture.js
 *Description:   发朋友圈.js
 *Others:        陈灿
 *************************************************/
    /*
     * 启动
     */
    mui.init();
    mui('.mui-scroll-wrapper').scroll({
        indicators: false,      //是否显示滚动条 默认为true
        deceleration: 0.003,    //阻尼系数,系数越小滑动越灵敏 默认0.0006
        bounce: false           //是否启用回弹 默认true
    });
    /*
     * 变量初始化
     */
    var that =getUrlParam('that');
    var type = '';
    if(that == 'v'){
        type = 'video';
    }else{
        type = 'image'
    }
    var files = [];
    var open = 'all';
    var uid = localStorage.replace_uid;
    var token = localStorage.replace_token;
    var video_type;
    /*
     * 主程序
     */ 
    $(document).ready(function() 
    {
        //样式加载
        pagecss();
        getface();
    });
    /**
     * pagecss
     * 样式加载
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    function pagecss(){
        $('.complaint-img-box').on('tap','.close',function(){
            $(this).parent().remove();
            if(that == 'v'){
                $('.complaint-add').parent('li').css({display:'block'});
            }else{
                if($('.complaint-p li').length<10){
                    $('.complaint-add').parent('li').css({display:'inline-block'});
                } 
            }
        })//删除照片
        
        
        function fontup(){
            $('.circlefriends .mui-scroll').css({'padding-bottom':'15rem'});
            $('.footer').css({height:'15rem'});
        }
        function fontdown(){
            $('.circlefriends .mui-scroll').css({'padding-bottom':'2.5rem'});
            $('.footer').css({height:'2.5rem'});
        }
        
        if(that == 'v'){
            $('.complaint-video').css({display:'block'})
        }else{
            $('.complaint-p').css({display:'block'})
        }
        
        
        $('.circlefriends').on('tap','.dialogue  .face-bq',function(){
            var othisimg = $(this).attr("src");
            var oval = $('.complaint-text').html();
            $('.complaint-text').html(oval+'<img class="face-bq" src="'+othisimg+'">')
            $('.complaint-text').removeClass('active');
        })
        
        
        
        $('.complaint-text').on('touchstart',function(){
            fontdown()
        }).on('input',function(){
            var param = $(this).text();
            var regRule = /\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g;
            if(param.match(regRule)) {
                param = param.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
                $(this).text(param)
            }
            if($(this).text().length>0||$(this).find('.face-bq').length>0){
                $(this).removeClass('active');
            }else{
                $(this).addClass('active');
            }
            
        })
        
//      $('.mui-title').on('tap',function(){
//          alert(JSON.stringify($('.complaint-text').html()))
//      })
        
        $('.friendpicture').on('tap','.face',function(){
            if(!$(this).hasClass('active')){
                $('.complaint-text').blur();
                fontup();
                $('.menu-box').css({display:'block'});
            }else{
                $('.complaint-text').fadeIn();
                fontdown()
            }
            $(this).toggleClass('active');
        })//表情等等点击上下
        
        var server = "http://replace-i.oss-cn-hangzhou.aliyuncs.com/";  //申请到的阿里云OSS地址
                    
        var OSSAccessKeyId= 'LTAIyJPvdRXd1eX9';     //申请到的阿里云AccessKeyId和AccessKeySecret
        var AccessKeySecret= 'Wkwdr687sxx0nK5RfWh5NiETPBAme3';//需要用自己申请的进行替换
        var files = [];  //存储文件信息的数组
        var fname = "";  //表示文件名，例如  XXXX.jpg;
        var dir ="app/";  //指定上传目录，此处指定上传到app目录下
        
        var testName;   //本地测试用的
        /*
         * 阿里云参数设置，用于计算签名signature
         */
        var policyText = {
            "expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
            "conditions": [
                ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
            ]
        };
        var policyBase64 = Base64.encode(JSON.stringify(policyText));
        var message = policyBase64;
        var bytes = Crypto.HMAC(Crypto.SHA1, message, AccessKeySecret, {
            asBytes: true
        });
        var signature = Crypto.util.bytesToBase64(bytes);

        //得到文件名的后缀
        function get_suffix(filename) {
            var pos = filename.lastIndexOf('.');
            var suffix = '';
            if(pos != -1) {
                suffix = filename.substring(pos)
            }
            return suffix;
        }

        // 拍照添加文件
        function appendByCamera() {
            plus.camera.getCamera().captureImage(function(p) {
                appendFile(p);
            });
        }
        // 从相册添加文件
        function appendByGallery() {
            plus.gallery.pick(function(p) {
                appendFile(p);
            });
        }
        // 添加文件
        var index = 1;

        function appendFile(p) {
            var fe = document.getElementById("files");
            // var li = document.createElement("li");
            // var n = p.substr(p.lastIndexOf('/') + 1);
            // fname = n;
            // li.innerText = n;
            // fe.appendChild(li);
            files.push({
                name: "uploadkey" + index,
                path: p
            });
            index++;
            // empty.style.display = "none";
        }
        
        $('.complaint .complaint-add').on('tap',function(){
            var obj = $(this);
            if(that == 'v'){
                common.actionSheet('选择上传','取消',[{title:'从相册获取'},{title:'拍摄'}],function(index){
                    localStorage.camopen="false";
                    if(index==1){
                        common.galleryvideo(function(src){
                            var img = '<li><a class="complaint-img"><div class="complaint-img-video"></div><video class="add" src="'+src+'"/></video></a><i class="close"></i></li>'
                            obj.parent().before(img);
                            $('.complaint-add').parent('li').css({display:'none'});
                            video_type='0';
                            appendFile(src);
                        })  
                    }else if(index==2){
                        common.videoCapture(function(src){
//                          var img = '<li><video class="add" src="'+src+'" ></video></li>'
                            var img = '<li><a class="complaint-img"><div class="complaint-img-video"></div><video class="add" src="'+src+'"/></video></a><i class="close"></i></li>'
                            obj.parent().before(img);
                            $('.complaint-add').parent('li').css({display:'none'});
                            video_type='1';
                            appendFile(src);
                        })  
                    }
                })  
            }else{
                common.actionSheet('选择上传','取消',[{title:'从相册获取'},{title:'拍照'}],function(index){
                    localStorage.camopen="false";
                    if(index==1){
                        common.galleryImg(function(src){
                            var img = '<li><a class="complaint-img"><img class="add" src="'+src+'"/></a><i class="close"></i></li>'
                            obj.parent().before(img);
                            if($('.complaint-p li').length>9){
                                $('.complaint-add').parent('li').css({display:'none'});
                            } 
                        })
                    }else if(index==2){
                        common.cameraImg(function(src){
                            var img = '<li><a class="complaint-img"><img class="add" src="'+src+'"/></a><i class="close"></i></li>'
                            obj.parent().before(img);
                            if($('.complaint-p li').length>9){
                                $('.complaint-add').parent('li').css({display:'none'});
                            } 
                        })
                    }
                })  
            }
        })
        
        $('.friendpicture .see').on('tap',function(){
            if($(this).attr('data-open') == 'all'){
                $(this).addClass('active').siblings().removeClass('active');
                open = $(this).attr('data-open');
            }else{
                if(open == 'all'){
                    $(this).addClass('active').siblings().removeClass('active');
                    open = $(this).attr('data-open');
                }else if(open == 'vipfriends'){
                    $(this).removeClass('active')
                    if($(this).attr('data-open') == 'vip'){
                        open = 'friends';
                    }else{
                        open = 'vip';
                    }
                }else{
                    if(!$(this).hasClass('active') && $(this).attr('data-open') != 'open'){
                        $(this).addClass('active');
                        open = 'vipfriends';
                    }
                }
            }
        })//发朋友圈查看权限
        
        $('.friendpicture .table-view-cell-a').on('tap',function(){
            $('.popover').fadeOut();
            $(this).attr('class')=='table-view-cell-a' ? $('.friendpicture .see').text($(this).text()) : false ;
        })//发朋友圈查看权限内容选择


        function videoUpload() {    //视频上传
            if(files.length <= 0) {
                plus.nativeUI.alert("没有添加上传文件！");
                return;
            }
            common.loadingIn();
            // mui.toast('开始上传：',{ duration:2000, type:'div' });
            // outSet("开始上传：")

            // var wt = plus.nativeUI.showWaiting();
            var task = plus.uploader.createUpload(server, {
                    method: "POST"
                },
                function(t, status) { //上传完成
                    console.log("t" + JSON.stringify(t));
                    if(status == 200) {
                        mui.toast('上传成功：' + t.responseText,{ duration:2000, type:'div' });
                        // outLine("上传成功：" + t.responseText);
                        //至此上传成功，上传后的图片完整地址为server+testName
                        var uploaderFileObj = {
                            "server":server,
                            "path":testName
                        };
                        console.log(t.responseText);
                        plus.storage.setItem("uploader", JSON.stringify(uploaderFileObj));
                        console.log(JSON.stringify(uploaderFileObj));
                        console.log(uploaderFileObj.path);
                        var file_url = uploaderFileObj.path;
                        articleAdd(uploaderFileObj.path);
                        // var w = plus.webview.create("uploader_ret.html", "uploader_ret.html", {
                        //     scrollIndicator: 'none',
                        //     scalable: false
                        // });
                        // w.addEventListener("loaded", function() {
                            // wt.close();
                            // w.show("slide-in-right", 300);
                        // }, false);
                    } else {
                        mui.toast('上传失败：' + status,{ duration:2000, type:'div' });
                        // outLine("上传失败：" + status);
                        // wt.close();
                    }
                }
            );
            var suffix1 = get_suffix(fname);  //文件后缀  例如   .jpg
            var keyname = dir + new Date().getTime() + suffix1;
            testName = keyname;
            
            //按照之前说明的参数类型，按顺序添加参数
            task.addData("key", keyname);
            task.addData("policy", policyBase64);
            task.addData("OSSAccessKeyId", OSSAccessKeyId);
            task.addData("success_action_status", "200");
            task.addData("signature", signature);
            var f = files[0];
            var filename=files[0].path;
            var index1=filename.lastIndexOf("."); 
            var index2=filename.length;
            var index3=filename.lastIndexOf("?"); 
            if(index3 > 0){
                var postf=filename.substring(index1+1,index3);//后缀名 
            }else{
                var postf=filename.substring(index1+1,index2);//后缀名 
            }
            
            // alert(postf);
            task.addFile(f.path, {
                key: "file",
                name: "file",
                mime: type+"/"+postf
            });

            task.start();
        }

        function articleAdd(path){
            console.log(111111);

            var otype = that == 'v' ? '2' : '1' ;
            var content = $(".complaint-text").html();
            // if(!$('.add').length&&!content){
            //     if(!content){
            //         mui.toast('说点什么吧！',{ duration:2000, type:'div' });
            //     }else{
            //         that == 'v' ? mui.toast('请添加视频！',{ duration:2000, type:'div' }):mui.toast('请添加图片！',{ duration:2000, type:'div' });
            //     }
            //     return;
            // }
            $.ajax({
                type: "post",
                url: DOMAIN_NAME +'/index.php/api/article/videoArticleAdd' ,
                dataType:'jsonp',
                data: {content: content, uid: uid, open: open, type: otype, url: path},
                success: function(data) {
                    if(data.error_code == 0){
                        mui.toast('发布成功',{ duration:2000, type:'div' });
                        setTimeout(function(){mui.back(),2000})
                    }else if(data.error_code == 1001){
                        setTimeout(function(){
                            exitlogin();
                        },1000);
                    }else{
                        $('.mui-slider-sitface').html('')
                    }
                    mui(".mui-slider").slider({interval: 0});
                }
            });
        }
        $('.complaint-btn').on('tap',function(){
            if(that == 'v'){
                videoUpload();
            }else{
                imagesUpload()
            }
            
        })
    }

    function imagesUpload(){
        var otype = that == 'v' ? '2' : '1' ;
        $('.complaint-text').blur();
        var content = $(".complaint-text").html();
        if(!$('.add').length&&!content){
            if(!content){
                mui.toast('说点什么吧！',{ duration:2000, type:'div' });
            }else{
                that == 'v' ? mui.toast('请添加视频！',{ duration:2000, type:'div' }):mui.toast('请添加图片！',{ duration:2000, type:'div' });
            }
            return;
        }else{
            common.loadingIn();
            var i = 1;
            var task = plus.uploader.createUpload(DOMAIN_NAME + "/index.php/api/article/articleAdd",
            { method:"POST",blocksize:204800,priority:200 },
                function (t, status) { //上传完成
                    common.loadingOut();
                    if (status == 200) {
                        mui.toast('发布成功',{ duration:2000, type:'div' });
                        setTimeout(function(){mui.back(),2000})
                    }else{
                        mui.toast('发布失败',{ duration:2000, type:'div' });
                    }
                }
            );
            if($('.add').length){
                files = [];
                $('.add').each(function(){
                    var path = $(this).attr('src');
                    task.addFile(path, {key: 'url'+i});
                    i++;
                })
            }
            task.addData("content", content);
            task.addData("uid", uid);
            task.addData("open", open);
            if(that == 'v'){
                task.addData("video_type", video_type);
            }
            task.addData("type", otype);
            mui.toast('开始上传',{ duration:2000, type:'div' });
            task.start();
        }
    }
    
    
     /**
     * 
     * 获取表情
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    function getface(){
        $.ajax({
            type: "post",
            url: DOMAIN_NAME +'/index.php/api/chat/getSystemExpressionsList' ,
            dataType:'jsonp',
            data: {},
            success: function(data) {
                var ohtml='';
                var oli ='';
                if(data.error_code == 0){
                    ohtml+='<div class="mui-slider-group"><div class="mui-slider-item">';
                    for(var i=0 ; i<data.data.length; i++){
                        if((i%21==0)&&(i!=0)){
                            ohtml+='</div><div class="mui-slider-item">';
                            oli+='<div class="mui-indicator"></div>';
                        }
                        ohtml+='<a data-id="'+data.data[i].id+'"><img class="face-bq" src="'+DOMAIN_NAME+data.data[i].url+'"></a>';
                    }
                    ohtml+='</div></div><div class="mui-slider-indicator"><div class="mui-indicator mui-active"></div>'+oli+'</div></div>';
                    $('.mui-slider-sitface').html(ohtml)
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }else{
                    $('.mui-slider-sitface').html('')
                }
                mui(".mui-slider").slider({interval: 0});
            }
        });
    }
    
    function set_focus(){
        el=document.getElementById('guestbook_editor');
        //el=el[0];  //jquery 对象转dom对象
        el.focus();
        if($.support.msie)
        {
            var range = document.selection.createRange();
            this.last = range;
            range.moveToElementText(el);
            range.select();
            document.selection.empty(); //取消选中
        }
        else
        {
            var range = document.createRange();
            range.selectNodeContents(el);
            range.collapse(false);
            var sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }